//
//  RegisterViewController.m
//  CarUser
//
//  Created by ayi on 2018/12/26.
//  Copyright © 2018 王森林. All rights reserved.
//

#import "RegisterViewController.h"

#import "SettingPasswordViewController.h"

#import <YYText/YYText.h>
#import "AgreementViewController.h"
@interface RegisterViewController ()

@property (weak, nonatomic) IBOutlet UIScrollView *scrollview;
@property (weak, nonatomic) IBOutlet UIView *phoneBgView;
@property (weak, nonatomic) IBOutlet UIView *passwordBgView;
@property (weak, nonatomic) IBOutlet UITextField *phonetextf;
@property (weak, nonatomic) IBOutlet UITextField *passwordtextf;//验证码
@property (weak, nonatomic) IBOutlet UIButton *senMessageBtn;//获取验证码
@property (weak, nonatomic) IBOutlet UIButton *nextBtn;//下一步


@property (nonatomic, strong) UIButton *selectedBtn;//选择按钮
@property (nonatomic, strong) YYLabel *authLab;//认证
@property (nonatomic, assign) NSInteger isGress;//1为tong意，2为不同意
@property (nonatomic, strong) UIButton *fuxuanBtn;
@end

@implementation RegisterViewController
{
    dispatch_source_t _timer;
}

- (void)dealloc{
    if (_timer != nil) {
        dispatch_source_cancel(_timer);
        _timer = nil;
    }
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"注册";
    
    self.phoneBgView.layer.masksToBounds = YES;
    self.phoneBgView.layer.cornerRadius = 22;
    
    self.passwordBgView.layer.masksToBounds = YES;
    self.passwordBgView.layer.cornerRadius = 22;
    
    self.senMessageBtn.titleLabel.font = FONT_SIZE(14);
    [self.senMessageBtn setTitleColor:RGB(50, 50, 50) forState:UIControlStateNormal];
    self.senMessageBtn.layer.masksToBounds = YES;
    self.senMessageBtn.layer.cornerRadius = 22;
    
    self.nextBtn.layer.masksToBounds = YES;
    self.nextBtn.layer.cornerRadius = 22;
    
    _authLab = [[YYLabel alloc]init];
    _authLab.numberOfLines = 0;
    
    self.fuxuanBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    UIImage *fuxuanimg = IMG(@"ic_unselect");
    self.fuxuanBtn.selected = YES;
    self.isGress = 1;
    [self.fuxuanBtn setImage:fuxuanimg forState:UIControlStateNormal];
    [self.fuxuanBtn setImage:IMG(@"ic_select") forState:UIControlStateSelected];
    self.fuxuanBtn.imageView.contentMode = UIViewContentModeCenter;
    [self.fuxuanBtn addTarget:self action:@selector(nativeAuthAction:) forControlEvents:UIControlEventTouchUpInside];
    objc_setAssociatedObject(self, @"fuxuanBtn", self.fuxuanBtn, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
    
    NSMutableAttributedString *tipsStr = [[NSMutableAttributedString alloc]initWithString:@"我已经阅读并同意用户服务协议" attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:13],NSForegroundColorAttributeName:RGB(242, 242, 242)}];
    [tipsStr addAttribute:NSUnderlineStyleAttributeName value:@(NSUnderlineStyleSingle) range:NSMakeRange(tipsStr.length - 6, 6)];
    
    @weakify(self);
    [tipsStr yy_setTextHighlightRange:NSMakeRange(tipsStr.length - 6, 6) color:RGB(242, 242, 242) backgroundColor:[UIColor whiteColor] tapAction:^(UIView * _Nonnull containerView, NSAttributedString * _Nonnull text, NSRange range, CGRect rect) {
        @strongify(self);
        AgreementViewController *controller = [[AgreementViewController alloc] init];
        controller.hidesBottomBarWhenPushed = YES;
        controller.resultBlock = ^(id  _Nonnull response) {
            self.fuxuanBtn.selected =  YES;
            self.isGress = 1;
        };
        [self.navigationController pushViewController:controller animated:YES];
        
    }];
    _authLab.attributedText = tipsStr;
    _authLab.textAlignment = NSTextAlignmentCenter;
    
    [self.scrollview addSubview:_authLab];
    [self.scrollview addSubview:self.fuxuanBtn];
    
    CGSize tipsSize = [CommonMethod labWidthFromAttributedString:tipsStr andWidth:BOUNDWIDTH - fuxuanimg.size.width - 6];
    
    [_authLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.nextBtn.mas_bottom).mas_equalTo(20);
        make.height.mas_equalTo(tipsSize.height);
        make.left.mas_equalTo(28 + 20);
        make.width.mas_equalTo(tipsSize.width);
    }];
    
    [self.fuxuanBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(self.authLab.mas_centerY).mas_offset(-1);
        make.right.equalTo(self.authLab.mas_left).offset(-2);
        make.width.mas_equalTo(fuxuanimg.size.width);
        make.height.mas_equalTo(ceilf(fuxuanimg.size.height));
    }];
    [self.fuxuanBtn expandSize:14];
    

    //下一步
    self.nextBtn.rac_command = [[RACCommand alloc]initWithSignalBlock:^RACSignal * _Nonnull(id  _Nullable input) {
        @strongify(self);
        
        RACSignal *sign = [RACSignal createSignal:^RACDisposable * _Nullable(id<RACSubscriber>  _Nonnull subscriber) {
            
            if (self.isGress == 2) {
                 [SVProgressHUD showErrorWithStatus:@"请同意用户协议"];
                [subscriber sendCompleted];
                return nil;
            }
            if ([self.phonetextf.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]].length == 0) {
                [CommonMethod shakeAnimationForView:self.phoneBgView];
                
                [subscriber sendCompleted];
                return nil;
            }
            
            if ([self.passwordtextf.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]].length == 0) {
                [CommonMethod shakeAnimationForView:self.passwordBgView];
                
                [subscriber sendCompleted];
                return nil;
            }
            
            NSDictionary *params = @{
                                     @"FKEY":[CommonMethod createMD5Key:@"mobile"],
                                     @"mobile":self.phonetextf.text,
                                     @"code":self.passwordtextf.text
                                     };
            
            dispatch_async(dispatch_get_main_queue(), ^{
                [SVProgressHUD showWithStatus:nil];
            });
            
            [[ZY_AfnNetManager shareInstance]postWithURL:Car_API_70 params:params md5Paraname:@"" success:^(id  _Nullable response) {
                [self startTimer];
                dispatch_async(dispatch_get_main_queue(), ^{
                    [SVProgressHUD dismiss];
                });
                [self performSegueWithIdentifier:@"settingpassword" sender:nil];
                
                [subscriber sendCompleted];
                
            } fail:^(NSError * _Nonnull error) {
                dispatch_async(dispatch_get_main_queue(), ^{
                    [SVProgressHUD showErrorWithStatus:error.localizedDescription];
                });
                [subscriber sendCompleted];
            }];
            
            return nil;
        }];
        return sign;
    }];
    //发送验证码
    self.senMessageBtn.rac_command = [[RACCommand alloc]initWithSignalBlock:^RACSignal * _Nonnull(id  _Nullable input) {
        @strongify(self);
        
        RACSignal *sign = [RACSignal createSignal:^RACDisposable * _Nullable(id<RACSubscriber>  _Nonnull subscriber) {
            
            if ([self.phonetextf.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]].length == 0) {
                [CommonMethod shakeAnimationForView:self.phoneBgView];
                
                [subscriber sendCompleted];
                return nil;
            }
            
            NSDictionary *params = @{
                                     @"FKEY":[CommonMethod createMD5Key:@"mobile"],
                                     @"mobile":self.phonetextf.text,
                                     @"type":@"1"
                                     };
            
            dispatch_async(dispatch_get_main_queue(), ^{
                [SVProgressHUD showWithStatus:nil];
            });
            
            [[ZY_AfnNetManager shareInstance]postWithURL:Car_API_CreateIdentifyCode params:params md5Paraname:@"" success:^(id  _Nullable response) {
                [self startTimer];
                dispatch_async(dispatch_get_main_queue(), ^{
                    [SVProgressHUD dismiss];
                });
                [subscriber sendCompleted];
                
            } fail:^(NSError * _Nonnull error) {
                dispatch_async(dispatch_get_main_queue(), ^{
                    [SVProgressHUD showErrorWithStatus:error.localizedDescription];
                });
                [subscriber sendCompleted];
            }];
            
            return nil;
        }];
        return sign;
        
    }];
}

- (void)nativeAuthAction:(UIButton *)btn{
    if (!btn.selected) {
        btn.selected =  YES;
        self.isGress = 1;
    } else {
        btn.selected = NO;
        self.isGress = 2;
        
    }
}








//倒计时
- (void)startTimer{
    __block int counts = 60;
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    _timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue);
    dispatch_source_set_timer(_timer, dispatch_walltime(NULL, 0), 1.0*NSEC_PER_SEC, 0);
    dispatch_source_set_event_handler(_timer, ^{
        dispatch_async(dispatch_get_main_queue(), ^{
            if (counts <= 0) {
                dispatch_source_cancel(self->_timer);
                self.senMessageBtn.enabled = YES;
                self.senMessageBtn.titleLabel.text = @"获取验证码";
                [self.senMessageBtn setTitle:@"获取验证码" forState:UIControlStateNormal];
                self.senMessageBtn.titleLabel.font = FONT_SIZE(14);
                [self.senMessageBtn setTitleColor:RGB(50, 50, 50) forState:UIControlStateNormal];
            }else{
                self.senMessageBtn.enabled = NO;
                self.senMessageBtn.titleLabel.text = [NSString stringWithFormat:@"%d秒后重新获取",counts];
                [self.senMessageBtn setTitle:[NSString stringWithFormat:@"%d秒后重新获取",counts] forState:UIControlStateNormal];
                [self.senMessageBtn setTitleColor:RGB(136, 136, 136) forState:UIControlStateNormal];
                self.senMessageBtn.titleLabel.font = FONT_SIZE(12);
            }
            counts --;
        });
    });
    dispatch_resume(_timer);
}


#pragma mark - Navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    if ([segue.identifier isEqualToString:@"settingpassword"]) {
       SettingPasswordViewController *push = segue.destinationViewController;
        push.mobile = self.phonetextf.text;
    }
}


@end
